package service;


import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import dao.Shangji;
import dao.User;
import dao.ShangjiDAO;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.security.MessageDigest;
import util.*;

public class ShangjiService {
	private ShangjiDAO ShangjiDao;
	public static Logger log = Logger.getLogger(ShangjiService.class);

	/*public Shangji isValid(String Shangjiname, String password) {
		List<Shangji> resultTemp = ShangjiDao.findByShangjiname(Shangjiname);
		Shangji Shangji;
		if (null==resultTemp || resultTemp.size()==0){
			return null;
		}
		else
			{
				Shangji=resultTemp.get(0);
				if (Shangji.getPassword().equals(password)){
					return Shangji;
				}
				else
					return null;
			}
	}*/
	
	public boolean shangjiInsert(User user,String shangjititle, String shangjikeyword,String shangjiinfo,int validDay) {
		Calendar calendar = Calendar.getInstance();
		Date submitdate = calendar.getTime();
		//Date submitDate = new Timestamp(System.currentTimeMillis());
		calendar.add(Calendar.DATE, validDay);	//有效期后
		Date deadline=calendar.getTime();
		String shangjistatus="pending";
		//Integer shangjiId=this.getMaxShangjiId()+1;
		String shangjicode=CodeCreate.createShangjiCode(user.getUserid(), submitdate);
		//System.out.println(new Integer(13).hashCode());
		Shangji shangji=new Shangji(user, shangjicode, deadline,
				submitdate, shangjititle,shangjikeyword, shangjiinfo,
				shangjistatus,null);
		//System.out.println(shangji);
//		(shangjiId,user,deadline,submitDate,content,shangjiStatus,title,keyword);
		ShangjiDao.save(shangji);
		return true;
	}
	
	public boolean shangjiDelete(int shangjiid) {
		Shangji shangji=ShangjiDao.findById(shangjiid);
		ShangjiDao.delete(shangji);
		return true;
	}
	
	public List<Shangji> shangjiQuery(final String keyword,final Date startDate,final Date endDate,final User user,final int index,final int pageSize) {
		List<Shangji> shangjis=null;
		final String queryString;
		//试试回调 (List)getHibernateTemplate().execute(new HibernateCallback(){public Object doInHibernate(Session session)throws HibernateException{} })
		if(keyword!=null && !keyword.equals("")) {
			queryString="from Shangji as s where s.user=? and s.shangjititle like ? order by submitdate desc";
			final String value="%"+keyword+"%";
			/*Session session=ShangjiDao.getHibernateTemplate().getSessionFactory().openSession();
			Query query=session.createQuery(queryString);
			query.setEntity(0, user);
			query.setString(1, value);
			query.setFirstResult((index-1)*pageSize);
			query.setMaxResults(pageSize);
			//shangjis=ShangjiDao.getHibernateTemplate().find(queryString,new Object[]{user,value});
			shangjis=query.list();
			session.close();*/
			shangjis=(List)ShangjiDao.getHibernateTemplate().execute(new HibernateCallback(){
				public Object doInHibernate(Session session)throws HibernateException{
					Query query=session.createQuery(queryString);
					query.setEntity(0, user);
					query.setString(1, value);
					query.setFirstResult((index-1)*pageSize);
					query.setMaxResults(pageSize);
					return query.list();
				} 
			});
			
		} else {
			queryString="from Shangji as s where s.user=? and"+" s.submitdate >=? and s.submitdate<=?";
			/*Session session=ShangjiDao.getHibernateTemplate().getSessionFactory().openSession();
			//Session session=HibernateSessionFactory.getSession();
			Query query=session.createQuery(queryString);
			query.setEntity(0, user);
			query.setDate(1,startDate);
			query.setDate(2,endDate);
			query.setFirstResult((index-1)*pageSize);
			query.setMaxResults(pageSize);
			//shangjis=ShangjiDao.getHibernateTemplate().find(queryString,new Object[]{user,sDate,eDate});
			shangjis=query.list();
			session.close();*/
			shangjis=(List)ShangjiDao.getHibernateTemplate().execute(new HibernateCallback(){
				public Object doInHibernate(Session session)throws HibernateException{
					Query query=session.createQuery(queryString);
					query.setEntity(0, user);
					query.setDate(1,startDate);
					query.setDate(2,endDate);
					query.setFirstResult((index-1)*pageSize);
					query.setMaxResults(pageSize);
					return query.list();
				} 
			});
		}
		
		return shangjis;
	}
	
	public PagingNum shangjiNumQuery(String keyword,Date startDate,Date endDate,User user,int index,int pageSize) {
		PagingNum pagingNum=new PagingNum();
		int totalNum,approveNum,denyNum,pageNum;
		String queryString;
		List total,approve,deny;
		
		if(keyword!=null && !keyword.equals("")) {
			queryString="select count(*) from Shangji as s where s.user=? and s.shangjikeyword like ?";
			String value="%"+keyword+"%";
			total=ShangjiDao.getHibernateTemplate().find(queryString,new Object[]{user,value});
			queryString="select count(*) from Shangji as s where s.user=? and s.shangjikeyword like ? and s.shangjistatus='approved'";
			approve=ShangjiDao.getHibernateTemplate().find(queryString,new Object[]{user,value});
			queryString="select count(*) from Shangji as s where s.user=? and s.shangjikeyword like ? and s.shangjistatus='deny'";
			deny=ShangjiDao.getHibernateTemplate().find(queryString,new Object[]{user,value});

		} else {
			queryString="select count(*) from Shangji as s where s.user=? and"+" s.submitdate >=? and s.submitdate<=?";
			total=ShangjiDao.getHibernateTemplate().find(queryString,new Object[]{user,startDate,endDate});
			queryString="select count(*) from Shangji as s where s.user=? and"+" s.submitdate >=? and s.submitdate<=? and s.shangjistatus='approved'";
			approve=ShangjiDao.getHibernateTemplate().find(queryString,new Object[]{user,startDate,endDate});
			queryString="select count(*) from Shangji as s where s.user=? and"+" s.submitdate >=? and s.submitdate<=? and s.shangjistatus='deny'";
			deny=ShangjiDao.getHibernateTemplate().find(queryString,new Object[]{user,startDate,endDate});

		}
		if(null==total||total.size()==0||total.isEmpty()||null==total.get(0))
			totalNum=0;
		else
			totalNum=((Long)total.get(0)).intValue();
		if(null==approve||approve.size()==0||approve.isEmpty()||null==approve.get(0))
			approveNum=0;
		else
			approveNum=((Long)approve.get(0)).intValue();
		if(null==deny||deny.size()==0||deny.isEmpty()||null==deny.get(0))
			denyNum=0;
		else
			denyNum=((Long)deny.get(0)).intValue();
		
		pageNum=totalNum/pageSize;
		if(totalNum%pageSize!=0)	pageNum++;
			
		pagingNum.setPageIndex(index);
		pagingNum.setApproveNum(approveNum);
		pagingNum.setDenyNum(denyNum);
		pagingNum.setTotalNum(totalNum);
		pagingNum.setPageNum(pageNum);
		pagingNum.setStartDate(startDate.toString());
		pagingNum.setEndDate(endDate.toString());
		
		int a[]=new int[5];
		int i=0;
		if(index-2>0)	a[i++]=index-2;
		if(index-1>0)	a[i++]=index-1;
		a[i++]=index;
		if(index+1<=pageNum)	a[i++]=index+1;
		if(index+2<=pageNum)	a[i++]=index+2;
		pagingNum.setPageIndexes(a);
		
		return pagingNum;
	}
	public int getMaxShangjiId() {
		int newShangjiId;
		String hql="select max(shangjiid) from Shangji";
		List list=ShangjiDao.getHibernateTemplate().find(hql);
		if(null==list||list.size()==0||list.isEmpty()||null==list.get(0))
			newShangjiId=0;
		else
			newShangjiId=((Integer)list.get(0)).intValue();
		return newShangjiId;
	}
	
	public ShangjiDAO getShangjiDao() {
		return ShangjiDao;
	}

	public void setShangjiDao(ShangjiDAO ShangjiDao) {
		this.ShangjiDao = ShangjiDao;
	}
}
